require "app_config"

class User < ActiveRecord::Base
 
  belongs_to :user_type
  has_many :ecases
  has_many :comments, :dependent => :destroy
  file_column :photo, :magick => { :geometry => "200x200" }
  validates_presence_of :login, :email, :user_type_id
  validates_uniqueness_of :login, :if => Proc.new {|user| user.login && !user.login.blank?} 
  validates_uniqueness_of :email, :if => Proc.new {|user| user.email && !user.email.blank?} 
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
  # when changing password
  validates_presence_of :password, :on => :update
  validates_confirmation_of :password, :on => :update

  def before_create
    self.password = User.encrypt(self.password) if self.password
  end
  
  # Returns encrypted (md5) value of passed string prefixed with USER_PASSWORD_PREFIX constant 
  def self.encrypt(pass)
    Digest::MD5.hexdigest(USER_PASSWORD_PREFIX + pass)
  end

  def name
    (first_name || "") + " " + (last_name || "")
  end

  def to_s
    name
  end

###################################
# Privileges

  def can_add_ecase?
    has_author_privs?
  end

  def can_add_comment?
    has_student_privs?
  end

  def can_edit_comment?(comment_)
    has_admin_privs? || (has_student_privs? && comment_.user.id == id)
  end

  def can_edit_ecase?(ecase_)
    has_admin_privs? || (has_author_privs? && ecase_.author.id == id)
  end

  def can_delete_ecase?(ecase_)
    has_admin_privs? || (has_author_privs? && ecase_.author.id == id)
  end

  def can_add_event?(ecase_)
    has_admin_privs? || (has_author_privs? && ecase_.author.id == id)
  end

  def can_edit_event?(event_)
    has_admin_privs? || (has_author_privs? && event_.author.id == id)
  end

  def can_delete_event?(event_)
    has_admin_privs? || (has_author_privs? && event_.author.id == id)
  end

  def can_add_resources?
    has_author_privs?
  end

  def can_edit_resources?(resource_)
    has_admin_privs? || (has_author_privs? && resource_.author.id == id)
  end

  def can_delete_resources?(resource_)
    has_admin_privs? || (has_author_privs? && resource_.author.id == id)
  end

# end of privileges
###################################

  def admin?
    user_type.id == UserType::ADMINISTRATOR[:id]
  end

  def author?
    user_type.id == UserType::AUTHOR[:id]
  end

  def teacher?
    user_type.id == UserType::TEACHER[:id]
  end

  def student?
    user_type.id == UserType::STUDENT[:id]
  end
  
  def has_admin_privs?
    admin?
  end

  def has_author_privs?
    author? || admin?
  end

  def has_teacher_privs?
    teacher? || author? || admin?
  end

  def has_student_privs?
    student? || teacher? || author? || admin?
  end
  
  def refresh
    User.find(id)
  end 
end